﻿

using System;
using AutoMapper;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;

using Oliving.Edge.AuthHelper;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models;
using Oliving.Edge.IServices;
using Oliving.Edge.Model.Dto;
using Oliving.Edge.IServices.User;
using Oliving.Edge.Model.Dto.User;
using Oliving.Edge.Model.Models.User;
using System.Linq.Expressions;
using Oliving.Edge.Common.Extensions;

namespace Oliving.Edge.Controllers
{
    [ApiController]
    [Route("api/Sys_Dept")]
    [Authorize(Permissions.Name)]
    public class Sys_DeptController : OlivingControll
    {
        IMapper _mapper;
        private readonly ISys_DeptServices _Sys_DeptServices;
        private readonly ILogger<Sys_DeptController> _logger;


        public Sys_DeptController(
                IHttpContextAccessor accessor, PermissionRequirement requirement,
                IMapper mapper, ILogger<Sys_DeptController> logger,
                ISys_DeptServices Sys_DeptServices
            ) : base(accessor, requirement)
        {
            _logger = logger;
            _mapper = mapper;
            _Sys_DeptServices = Sys_DeptServices;
        }



        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/Get")]
        public async Task<MessageModel<Sys_DeptDto>> Get(string id)
        {
            var data = new MessageModel<Sys_DeptDto>();
            Sys_Dept model = await _Sys_DeptServices.QueryById(id);
            if (model == null)
            {
                data.response = null;
                data.msg = "数据不存在！";
                data.success = false;
            }
            else
            {
                var dto = _mapper.Map<Sys_DeptDto>(model);
                data.response = dto;
                data.msg = "获取成功！";
                data.success = true;
            }
            return data;
        }




        [HttpGet]
        [AllowAnonymous]
        [Route("/api/[controller]/GetList")]
        public async Task<MessageModel<List<Sys_Dept_ComProPageDto>>> GetList(
            string ProID = "",
            string ComID = "")
        {
            var data = new MessageModel<List<Sys_Dept_ComProPageDto>>();

            Expression<Func<Sys_Dept, bool>> whereExpression = _Sys_Dept => true;



            if (string.IsNullOrEmpty(ProID) || string.IsNullOrWhiteSpace(ProID))
            {

            }
            else
            {
                whereExpression = whereExpression.And(d => d.ProID == ProID);
            }


            if (string.IsNullOrEmpty(ComID) || string.IsNullOrWhiteSpace(ComID))
            {

            }
            else
            {
                whereExpression = whereExpression.And(d => d.ComID == ComID);
            }

            whereExpression = whereExpression.And(d => d.DeleteMark == 0);
            List<Sys_Dept_ComProPageDto> list = await _Sys_DeptServices.GetList_ComPro(whereExpression);
 
            List<Sys_Dept_ComProPageDto> listChild = list.ConvertTreeList("", "Id", "Pid", "children");
            data.response = listChild;
            data.msg = "获取成功！";
            data.success = true;

            return data;
        }






        [HttpGet]
        [Route("/api/[controller]/GetPageList")]
        public async Task<MessageModel<PageModel<Sys_DeptPageDto>>> GetPageList(
            int page = 1, int PageSize = 20, string sidx = "", string order = "", string key = "",
            string ProID = "",
            string ComID = ""
            )
        {
            Expression<Func<Sys_Dept, bool>> whereExpression = _Sys_Dept => true;
            if (string.IsNullOrEmpty(ProID) || string.IsNullOrWhiteSpace(ProID))
            {

            }
            else
            {
                whereExpression = whereExpression.And(d => d.ProID == ProID);
            }


            if (string.IsNullOrEmpty(ComID) || string.IsNullOrWhiteSpace(ComID))
            {

            }
            else
            {
                whereExpression = whereExpression.And(d => d.ComID == ComID);
            }



            var data = await _Sys_DeptServices.QueryPageList(whereExpression, page, PageSize, sidx, order);

            return new MessageModel<PageModel<Sys_DeptPageDto>>()
            {
                msg = "获取成功",
                success = true,
                response = data
            };
        }



        [HttpPut]
        [Route("/api/[controller]/Update")]
        public async Task<MessageModel<string>> Update([FromBody] Sys_DeptDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && !string.IsNullOrEmpty(dto.Id))
            {
                Sys_Dept model = await _Sys_DeptServices.QueryById(dto.Id);
                if (model != null)
                {
                    model.Pid = dto.Pid;
                    model.DeptName = dto.DeptName;
                    model.ProID = dto.ProID;
                    model.ComID = dto.ComID;



                    data.success = await _Sys_DeptServices.Update(model);

                    if (data.success)
                    {
                        data.msg = "更新成功";
                        data.response = dto.Id.ObjToString();
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "参数异常，您要更新的数据不存在";
                }
            }
            else
            {
                data.success = false;
                data.msg = "参数异常";
            }
            return data;
        }



        [HttpPost]
        [Route("/api/[controller]/Add")]
        public async Task<MessageModel<string>> Add(Sys_Dept dto)
        {
            var data = new MessageModel<string>();

            int id = await _Sys_DeptServices.AddGuid(dto);

            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }
            return data;
        }




        [HttpDelete]
        [Route("/api/[controller]/Delete")]
        public async Task<MessageModel<string>> Delete(string id)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(id))
            {
                var userDetail = await _Sys_DeptServices.QueryById(id);
                userDetail.DeleteMark = 1;
                data.success = await _Sys_DeptServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.Id.ObjToString();
                }
            }
            return data;
        }





        [HttpDelete]
        [Route("/api/[controller]/BatchDelete")]
        public async Task<MessageModel<string>> BatchDelete(string ids)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                if (false)
                {
                    #region 软删除

                    int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s));

                    Sys_Dept model = new Sys_Dept();
                    //  model.C_State = -1;          ???????????????????
                    string whereStr = " Id in (" + ids + ")";
                    List<string> colList = new List<string>();
                    //  colList.Add("C_State");    ???????????????????
                    List<string> colHL = new List<string>();

                    bool isOK = await _Sys_DeptServices.Update(model, colList, colHL, whereStr);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }
                {
                    #region 直接删除 

                    object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                    bool isOK = await _Sys_DeptServices.DeleteByIds(list);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }
                    #endregion
                }
            }
            return data;
        }




    }
}

